package com.lp.rpc.registry;

import com.lp.rpc.constants.LpConstant;
import com.lp.rpc.domain.result.LpCode;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务本地缓存
 *
 * @author 刘牌
 * @version 1.0
 * @date 2021/8/28 0028 0:02
 */
public class LocalServiceCache {
    private static final ConcurrentHashMap<String,Object> serviceMap;

    private static final Timer timer;

    static {
        serviceMap = new ConcurrentHashMap<>();
        timer = new Timer();
    }
    private LocalServiceCache(){}

    /**
     * 添加cache
     * @param key
     */
    public static void put(String key , Object o){
        serviceMap.put(key,o);
    }

    public static void putBatch(Map<String,Object> map){
        serviceMap.putAll(map);
    }

    /**
     * 删除所有缓存
     * @param
     */
    public void clearAll(){
        timer.cancel();
    }

    /**
     * 获取服务
     * @param key
     * @return
     */
    public static Map<String,Object> getService(String key){
        Object value = serviceMap.get(key);
        Map<String,Object> map = new HashMap<>();
        if (value != null){
            String[] strings = value.toString().split(":");
            map.put(LpConstant.HOST,strings[0]);
            map.put(LpConstant.PORT,Integer.valueOf(strings[1]));
            map.put(LpConstant.SERVICE,strings[2]);
            return map;
        }
        return map;
    }


    /**
     * 判断缓存是否存在
     * @param key
     */
    public static boolean contain(String key){
        return serviceMap.contains(key);
    }

    /**
     * 移除缓存
     * @param key
     */
    public static void remove(String key){
        serviceMap.remove(key);
    }



}
